
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed


(function(){
  
  
  var mt = {}, tmpl = {}, cache = {}, fileModifiedCache ={}, templateFolder, templateExt;
 
  tmpl.render = function render(str, data, secret){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    
    if(!secret){
    	var modified = new java.io.File(templateFolder + "/" + str + "." + templateExt).lastModified();
    		
    	if(cache[str]){
    		if(fileModifiedCache[str] != modified){
    			fileModifiedCache[str] = modified
    			cache[str] = null;
    		}
    	} else {
    		fileModifiedCache[str] = modified;
    	}
    }
    var fn = (!secret) ?
      cache[str] = cache[str] ||
        render(com.ashafa.fileutils.FetchFile.readFile(templateFolder + "/" + str + "." + templateExt, ""), null, true) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      (function(){
      	
      	var tstr = new String(str);
      	//alert(tstr.match(/r/).length)
      	var funcStr = "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        tstr
          .replace(/\r\n|[\r\n]/g, "\\n")
          .split("\t").join(" ")
          .split("\\").join("\\\\")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .split("'").join("\\'")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
          .split("\\\\n").join("\\n")
        + "');}return p.join('');"
      	
          return new Function("obj", funcStr);
       
      })();
      
         
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
    
    
  };
  
  mt.init = function(args){
  	if(args){
  		templateFolder = args.templateFolder;
  		templateExt = args.templateExtenstion || "tmpl";
  	}
 	return tmpl;   	
  }
  
  window.MicroTemplate = mt;
	  
 
})();
